package org.apache.servicecomb.samples.practise.houserush.gateway.dispatcher;

import io.vertx.ext.web.Cookie;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.CookieHandler;
import org.apache.servicecomb.edge.core.AbstractEdgeDispatcher;
import org.apache.servicecomb.edge.core.EdgeInvocation;

import java.util.Map;

public class ApiDispatcher extends AbstractEdgeDispatcher {
    @Override
    public int getOrder() {
        //返回数字越小，执行优先级越高
        return 10002;
    }

    @Override
    public void init(Router router) {
        //regex = "/" + prefix + "/([^\\\\/]+)/([^\\\\/]+)/(.*)";//匹配带版本号的请求

        String regex = "/([^\\\\/]+)/(.*)";//不带版本号的请求

        router.routeWithRegex(regex).handler(CookieHandler.create());
        router.routeWithRegex(regex).handler(createBodyHandler());
        router.routeWithRegex(regex).failureHandler(this::onFailure).handler(this::onRequest);

    }

    private void onRequest(RoutingContext context) {
        Map<String, String> pathParams = context.pathParams();
        String microserviceName = pathParams.get("param0");
        String path = "/" + pathParams.get("param1");

        EdgeInvocation edgeInvocation = new EdgeInvocation() {
            @Override
            protected void setContext() throws Exception {
                super.setContext();
                //从请求头中获取token或者从cookie中获取token，添加到context上下文中
                String token = context.request().getHeader("Authorization");


                //从请求头中获取token
                if(token != null) {
                    this.invocation.addContext("Authorization",token);
                } else {
                //如果拿不到再从cookie中获取token
                    Cookie cookie = context.getCookie("Authorization");
                    if(cookie != null) {
                        this.invocation.addContext("Authorization",cookie.getValue());
                    }
                }
                context.request().headers().add("customerId","-1");

            }
        };

        edgeInvocation.init(microserviceName, context, path, httpServerFilters);
        edgeInvocation.edgeInvoke();
    }
}
